package com.yummy.cloud.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

@Configuration
public class GatewayLimitConfiguration {

	@Bean
	public KeyResolver keyResolver() {
		return new RouteIdResolver();
	}
	
	public static class RouteIdResolver implements KeyResolver{

		@Override
		public Mono<String> resolve(ServerWebExchange exchange) {
			Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
			return Mono.just(route)
					.switchIfEmpty(Mono.empty())
					.map(r->r.getId());
		}
		
	}
}
